export function isPrimative(val: any) {
  const isObject = ['Object', 'Array'].includes(
    Object.prototype.toString.call(val).slice(8, -1),
  )
  return !isObject
}

export function camelCase(str: string) {
  return str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase())
}

export function capitalize(str: string) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

export function titleCase(str: string) {
  return capitalize(str).replace(/[-_](\w)/g, (_, c) => ' ' + c.toUpperCase())
}

export const isPlainObject = (val: any) => {
  return Object.prototype.toString.call(val).slice(8, -1) === 'Object'
}

export const pickData = (data: Obj, keys: Array<string>, defVal = '') => {
  return keys.reduce((result, key) => {
    result[key] = data[key] === undefined ? defVal : data[key]
    return result
  }, {} as Obj)
}

export const omitData = (data: Obj, keys: Array<string>) => {
  const keepKeys = Object.keys(data).filter((key) => !keys.includes(key))
  return pickData(data, keepKeys)
}

export const sleep = (seconds = 1) => {
  return new Promise((resolve) => setTimeout(resolve, seconds * 1000))
}

export function setDefaults<T extends Obj>(data: T, defaultData: Obj): T {
  Object.keys(defaultData).forEach((key) => {
    const value = data[key]
    if (value == undefined) {
      // @ts-ignore
      data[key] = defaultData[key]
    }
  })

  return data
}

export function uuid(len = 8) {
  return Array.from({ length: len + 1 })
    .join('x')
    .replace(/[x]/g, () => {
      const r = (Math.random() * 16) | 0
      return r.toString(16)
    })
}

export function getRandomInt(min: number, max: number) {
  return min + Math.floor(Math.random() * (max - min + 1))
}

export function getRandomItem<T>(arr: T[]): T {
  return arr[getRandomInt(0, arr.length - 1)]
}

export function getRandomStars(
  min: number,
  max: number,
  step = 0.5,
  fixedLen = 1,
) {
  let n = min
  const allStars = []
  while (n <= max) {
    allStars.push(fixedLen ? n.toFixed(fixedLen) : n + '')
    n += step
  }
  return allStars[getRandomInt(0, allStars.length - 1)]
}

export function shuffleArray<T>(array: T[]): T[] {
  return array.sort(() => Math.random() - 0.5)
}
